package tulingxueyuan117;

import sun.security.util.Length;

import java.util.ArrayList;
import java.util.Stack;

/**
 * Author: Zhang Dongwei
 * Date: 2022/10/23 20:27
 * 给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false 。
 */
public class p17_回文链表_234 {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(1);

        listNode.next = listNode1;
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        boolean res = isPalindrome(listNode);
        System.out.println(res);
    }

//    先用数组保存，然后再前后双指针
    public static boolean isPalindrome1(ListNode head) {
        ArrayList<Integer> list = new ArrayList<>();
//        ListNode currentNode = head;
        while (head!=null){
            list.add(head.val);
            head = head.next;
        }
        int front = 0;
        int back = list.size()-1;
        while (front<back){
//            if(list.indexOf(front)!=list.indexOf(back)) {
            if(!list.get(front).equals(list.get(back))) {
                return false;
            }
            front ++;
            back --;
        }
        return true;
    }

//    视频解法
    public static boolean isPalindrome(ListNode head) {
        ListNode fast = head, slow = head;
        while (fast!=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        if(fast!=null){
            slow = slow.next;
        }
        slow = reverseList(slow);
        fast = head;

        while (slow!=null){
            if(fast.val != slow.val){
                return false;
            }
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    public static ListNode reverseList(ListNode head) {
        ListNode preNode = null;
        ListNode curr = head;
        while (curr!=null){
            ListNode next = curr.next;
            curr.next = preNode;
            preNode = curr;
            curr = next;
        }
        return preNode;
    }
}
